package com.laowang.project.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.laowang.common.utils.SecurityUtils;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.system.domain.MyCyhActivity;
import com.laowang.project.system.domain.WxUser;
import com.laowang.project.system.service.MyCyhActivityService;
import com.laowang.project.system.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.UserGoldLog;
import com.laowang.project.system.service.UserGoldLogService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * 用户金币变动记录Controller
 *
 * @author laowang
 * @date 2023-06-07
 */
@Api(tags = "用户金币变动记录接口")
@RestController
@RequestMapping("/goldLog")
public class UserGoldLogController extends BaseController {
    @Autowired
    private UserGoldLogService userGoldLogService;

    @Autowired
    private MyCyhActivityService myCyhActivityService;

    @Autowired
    private WxUserService wxUserService;

    @ApiOperation(value = "小程序端 累计收入",notes = "")
    @GetMapping("/income")
    public AjaxResult income() {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        UserGoldLog userGoldLog = new UserGoldLog();
        userGoldLog.setUserId(mid);
        //userGoldLog.setCreated(new Date());
        userGoldLog.setPageNum(null);
        userGoldLog.setPageNum(null);
        List<UserGoldLog> userGoldLogs = userGoldLogService.selectUserGoldLogListWeb(userGoldLog);
        Integer i= 0;
        for (UserGoldLog goldLog : userGoldLogs) {
            if (goldLog.getChangeBalance().intValue() >0){
                i += goldLog.getChangeBalance().intValue();
            }
        }

        return AjaxResult.success("操作成功",i);
    }


    @ApiOperation(value = "小程序端 今日收入",notes = "")
    @GetMapping("/toadyIncome")
    public AjaxResult toadyIncome() {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        UserGoldLog userGoldLog = new UserGoldLog();
        userGoldLog.setUserId(mid);
        userGoldLog.setCreated(new Date());
        userGoldLog.setPageNum(null);
        userGoldLog.setPageNum(null);
        List<UserGoldLog> userGoldLogs = userGoldLogService.selectUserGoldLogListWeb(userGoldLog);
        Integer i= 0;
        for (UserGoldLog goldLog : userGoldLogs) {
            if (goldLog.getChangeBalance().intValue() >0){
                i += goldLog.getChangeBalance().intValue();
            }
        }

        return AjaxResult.success("操作成功",i);
    }

    @ApiOperation(value = "小程序端 已提现",notes = "")
    @GetMapping("/hasWithdrawn")
    public AjaxResult hasWithdrawn() {

        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        UserGoldLog userGoldLog = new UserGoldLog();
        userGoldLog.setUserId(mid);
        userGoldLog.setStatus(1);
        userGoldLog.setPageNum(null);
        userGoldLog.setPageNum(null);
        List<UserGoldLog> userGoldLogs = userGoldLogService.selectUserGoldLogList(userGoldLog);
        Integer i= 0;
        for (UserGoldLog goldLog : userGoldLogs) {

            i += goldLog.getChangeBalance().intValue();

        }

        return AjaxResult.success("操作成功",Math.abs(i) );
    }

    @ApiOperation(value = "小程序端 查询用户金币冻结状态",notes = "")
    @GetMapping("/queryFrozen")
    public AjaxResult queryFrozen() {
        Map<Integer,MyCyhActivity> map =new HashMap<>();
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        UserGoldLog userGoldLog =new UserGoldLog();
        userGoldLog.setUserId(mid);
        userGoldLog.setStatus(2);
        List<UserGoldLog> list = userGoldLogService.selectUserGoldLogList(userGoldLog);
        Integer fg= 0;
        Integer flag =0;
        for (UserGoldLog goldLog : list) {
            if (goldLog.getType().equals(2)){
                fg += goldLog.getChangeBalance().intValue();
                MyCyhActivity myCyhActivity1 = map.get(Integer.valueOf(goldLog.getFromSourceId()));
                if (myCyhActivity1 == null){
                    MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(goldLog.getFromSourceId()));

                    if (myCyhActivity != null){
                        map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity);
                        if (myCyhActivity.getAtimeEnd().before(new Date())){
                           flag =1;
                        }
                    }


                }else {
                    //map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity1);
                    if (myCyhActivity1.getAtimeEnd().before(new Date())){
                        flag =1;
                    }
                }

            }
        }
        return AjaxResult.success("操作成功",String.valueOf(fg)+"_"+flag);
    }

    @ApiOperation(value = "小程序端 解冻金币",notes = "")
    @GetMapping("/thawGold")
    public AjaxResult thawGold(Integer goldId) {
        UserGoldLog userGoldLog1 = userGoldLogService.selectUserGoldLogById(goldId);
        if (userGoldLog1 == null ){
            return AjaxResult.error("参数有误");
        }
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();

        if (!userGoldLog1.getUserId().equals(mid)){
            return AjaxResult.error("不能操作他人的金币");
        }
        if (!userGoldLog1.getStatus().equals(2)){
            return AjaxResult.error("此记录金币没有冻结");
        }
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(userGoldLog1.getFromSourceId()));
        if (myCyhActivity.getAtimeEnd().before(new Date())){
            synchronized (this){
                int i = userGoldLog1.getChangeBalance().intValue();
                userGoldLog1.setStatus(1);//可提现
                userGoldLogService.updateUserGoldLog(userGoldLog1);
                WxUser wxUser = wxUserService.selectWxUserById(mid);
                Integer goldCoin = wxUser.getGoldCoin();
                goldCoin += i;
                wxUser.setGoldCoin(goldCoin);
                wxUserService.updateWxUser(wxUser);
            }

            return AjaxResult.success("操作成功");
        }else {
            return AjaxResult.error("活动未结束暂不能解冻");
        }
    }


    @ApiOperation(value = "小程序端 查询用户金币变动记录列表",notes = "")
    @GetMapping("/record")
    public TableDataInfoMy record(UserGoldLog userGoldLog) {

        //UserGoldLog userGoldLog = new UserGoldLog();
        if  (userGoldLog == null){
            userGoldLog = new UserGoldLog();
        }
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        userGoldLog.setUserId(mid);

        startPage();
        List<UserGoldLog> list = userGoldLogService.selectUserGoldLogListWeb(userGoldLog);

        Map<Integer,MyCyhActivity> map =new HashMap<>();
        for (UserGoldLog goldLog : list) {
            if (goldLog.getType().equals(2)){
                MyCyhActivity myCyhActivity1 = map.get(Integer.valueOf(goldLog.getFromSourceId()));
                if (myCyhActivity1 == null){
                    MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(goldLog.getFromSourceId()));
                    if (myCyhActivity != null){
                        goldLog.setActivityName(myCyhActivity.getTitle());
                        goldLog.setActivityEndTime(myCyhActivity.getAtimeEnd());
                        map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity);
                    }

                }else {
                    goldLog.setActivityName(myCyhActivity1.getTitle());
                    goldLog.setActivityEndTime(myCyhActivity1.getAtimeEnd());
                    //map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity1);
                }

            }
        }
        return getDataTableMy(list);
    }


    /**
     * 查询用户金币变动记录列表
     */
    @ApiOperation(value = "查询用户金币变动记录列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserGoldLog userGoldLog) {
        startPage();
        List<UserGoldLog> list = userGoldLogService.selectUserGoldLogList(userGoldLog);
        Map<Integer,MyCyhActivity> map =new HashMap<>();
        for (UserGoldLog goldLog : list) {
            if (goldLog.getType().equals(2)){
                MyCyhActivity myCyhActivity1 = map.get(Integer.valueOf(goldLog.getFromSourceId()));
                if (myCyhActivity1 == null){
                    MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(goldLog.getFromSourceId()));
                    if (myCyhActivity != null){
                        goldLog.setActivityName(myCyhActivity.getTitle());
                        goldLog.setActivityEndTime(myCyhActivity.getAtimeEnd());
                        map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity);
                    }

                }else {
                    goldLog.setRemark(myCyhActivity1.getTitle());
                    goldLog.setActivityEndTime(myCyhActivity1.getAtimeEnd());
                    //map.put(Integer.valueOf(goldLog.getFromSourceId()),myCyhActivity1);
                }

            }
        }
        return getDataTable(list);
    }

    /**
     * 导出用户金币变动记录列表
     */
    @ApiOperation(value = "导出用户金币变动记录列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:export')")
    @Log(title = "用户金币变动记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(UserGoldLog userGoldLog) {
        List<UserGoldLog> list = userGoldLogService.selectUserGoldLogList(userGoldLog);
        ExcelUtil<UserGoldLog> util = new ExcelUtil<UserGoldLog>(UserGoldLog.class);
        return util.exportExcel(list, "goldLog");
    }

    /**
     * 获取用户金币变动记录详细信息
     */
    @ApiOperation(value = "获取用户金币变动记录详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(userGoldLogService.selectUserGoldLogById(id));
    }

    /**
     * 新增用户金币变动记录
     */
    @ApiOperation(value = "新增用户金币变动记录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:add')")
    @Log(title = "用户金币变动记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserGoldLog userGoldLog) {
        return toAjax(userGoldLogService.insertUserGoldLog(userGoldLog));
    }

    /**
     * 修改用户金币变动记录
     */
    @ApiOperation(value = "修改用户金币变动记录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:edit')")
    @Log(title = "用户金币变动记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserGoldLog userGoldLog) {
        return toAjax(userGoldLogService.updateUserGoldLog(userGoldLog));
    }

    /**
     * 删除用户金币变动记录
     */
    @ApiOperation(value = "删除用户金币变动记录",notes = "")
    @PreAuthorize("@ss.hasPermi('my:goldLog:remove')")
    @Log(title = "用户金币变动记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(userGoldLogService.deleteUserGoldLogByIds(ids));
    }
}
